package com.jhf.skypac_pda;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.elvishew.xlog.XLog;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.google.gson.Gson;
import com.jhf.skypac_pda.EventMessage.MessageEvent;
import com.jhf.skypac_pda.adapter.NewOrderDetailListAdapter;
import com.jhf.skypac_pda.base.BaseActivity;
import com.jhf.skypac_pda.db.bean.DB_OperationRecord;
import com.jhf.skypac_pda.db.impl.OperationRecordDaoImp;
import com.jhf.skypac_pda.db.impl.PermissionDaoImp;
import com.jhf.skypac_pda.model.DialogCallback;
import com.jhf.skypac_pda.model.EventSourceModel;
import com.jhf.skypac_pda.model.FeedRecord;
import com.jhf.skypac_pda.model.JsonCallback;
import com.jhf.skypac_pda.model.LzyResponse;
import com.jhf.skypac_pda.model.OrderDetailModel;
import com.jhf.skypac_pda.utils.ConstantPara;
import com.jhf.skypac_pda.utils.PrefUtils;
import com.jhf.skypac_pda.utils.Urls;
import com.symbol.emdk.EMDKManager;
import com.symbol.emdk.EMDKResults;
import com.symbol.emdk.barcode.BarcodeManager;
import com.symbol.emdk.barcode.ScanDataCollection;
import com.symbol.emdk.barcode.Scanner;
import com.symbol.emdk.barcode.ScannerConfig;
import com.symbol.emdk.barcode.ScannerException;
import com.symbol.emdk.barcode.ScannerInfo;
import com.symbol.emdk.barcode.ScannerResults;
import com.symbol.emdk.barcode.StatusData;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okgo.OkGo;
import okgo.model.HttpHeaders;
import okgo.model.Response;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import okhttp3.sse.EventSources;

import static com.jhf.skypac_pda.EventMessage.MessageEvent.ORDERID;
import static com.jhf.skypac_pda.utils.ConstantPara.JSON;

public class NewFeedingDetailActivity extends BaseActivity implements EMDKManager.EMDKListener, Scanner.DataListener, Scanner.StatusListener, BarcodeManager.ScannerConnectionListener{
    @BindView(R.id.order_id)
    TextView order_id;
    @BindView(R.id.tank_num)
    TextView tank_num;
    @BindView(R.id.need_origin)
    TextView need_origin;
    @BindView(R.id.order_status)
    TextView order_status;
    @BindView(R.id.three_status)
    TextView three_status;
    @BindView(R.id.tv_back)
    TextView tv_back;
    @BindView(R.id.bag_num)
    TextView bag_num;
    @BindView(R.id.stop_feeding)
    TextView stop_feeding;
    @BindView(R.id.start_feeding)
    TextView start_feeding;
    @BindView(R.id.rv_data)
    RecyclerView rvData;
    @BindView(R.id.ll_empty)
    LinearLayout imgEmpty;
    @BindView(R.id.ll_button)
    LinearLayout ll_button;
    @BindView(R.id.ll_bag_num_obtain)
    LinearLayout ll_bag_num_obtain;
    @BindView(R.id.ll_three_obtain)
    LinearLayout ll_three_obtain;
    @BindView(R.id.ll_record_list)
    RelativeLayout ll_record_list;

    private AtomicBoolean initFlag = new AtomicBoolean(false);

    private EMDKManager emdkManager = null;

    private BarcodeManager barcodeManager = null;
    private Scanner scanner = null;

    public ScannerInfo readScannerInfo;

    private boolean bSoftTriggerSelected = false;
    private boolean bExtScannerDisconnected = false;
    private final Object lock = new Object();
    private String orderId = "";
    private String materialTankFeedingOrderCode = "";
    private String materialTankNum = "";

    private List<DB_OperationRecord> mList = new ArrayList<>();
    private NewOrderDetailListAdapter mAdapter;
    private EventSource eventSource;

    private ProgressDialog dialog;
    private boolean isShowing = false;
    private boolean isFullShowing = false;

    private OrderDetailModel orderDetailModel = new OrderDetailModel();

    private Timer timer;

    @Override
    protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState != null) {
            orderId = savedInstanceState.getString("orderId");
            orderDetailModel = (OrderDetailModel) savedInstanceState.getSerializable("orderDetailModel");

            materialTankFeedingOrderCode = orderDetailModel.getMaterialTankFeedingOrderCode();
            order_id.setText(materialTankFeedingOrderCode);
            materialTankNum = orderDetailModel.getMaterialTankNum();
            tank_num.setText(materialTankNum);
            bag_num.setText((int)orderDetailModel.getMaterialTankFeedingBagCount() + "");
            need_origin.setText(orderDetailModel.getMaterialTankFeedingOrderSourceDesc());
            order_status.setText(orderDetailModel.getMaterialTankFeedingOrderStatusDesc());

            if (eventSource == null) {
                initEventSource();
            }

            if (emdkManager == null || scanner == null || barcodeManager == null) {
                deInitScanner();
                deInitBarcodeManager();
                if (emdkManager != null) {
                    emdkManager.release();
                    emdkManager = null;
                    initFlag.set(false);
                }

                initZebra(this);
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("orderId", orderId);
        outState.putSerializable("orderDetailModel", orderDetailModel);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feeding_detail_new);
        ButterKnife.bind(this);
        // 隐藏导航栏
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
        decorView.setSystemUiVisibility(uiOptions);

        LinearLayoutManager manager = new LinearLayoutManager(this);
        rvData.setLayoutManager(manager);
        //mAdapter = new OrderDetailListAdapter(this, mList);
        mAdapter = new NewOrderDetailListAdapter(R.layout.orderdetail_list_item_new, mList);
        rvData.setAdapter(mAdapter);
        //rvData.setPullRefreshEnabled(false);

        orderId = getIntent().getStringExtra("orderId");
        getData(orderId);
        //测试
        //orderId = "1845731623733227520";

        initZebra(this);
        initEventSource();
        initTimer();
    }

    private void initTimer() {
        timer=new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                getBagCount();
            }
        },0,30000);
    }

    private void initEventSource() {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.MINUTES)
                .build();

        Request request = new Request.Builder()
                .url(Urls.SERVER + "erp/materialtankplc/sse/" + orderId) // 替换为你的 SSE 服务器 URL
                .build();

        EventSource.Factory factory = EventSources.createFactory(client);
        eventSource = factory.newEventSource(request, new EventSourceListener() {
            @Override
            public void onClosed(@NotNull EventSource eventSource) {
                super.onClosed(eventSource);
            }

            @Override
            public void onEvent(@NotNull EventSource eventSource, @Nullable String id, @Nullable String type, @NotNull String data) {
                super.onEvent(eventSource, id, type, data);
                if (data != null) {
                    Gson gson = new Gson();
                    EventSourceModel eventSourceModel = gson.fromJson(data, EventSourceModel.class);
                    //XLog.i("eventSourceModel content = " + eventSourceModel.toString());
                    Log.i("eventSourceModel content = ", eventSourceModel.toString());
                    if (eventSourceModel.getShow().equals("N")) {
                        return;
                    } else {
                        if(isShowing) return;

                        String ev = eventSourceModel.getOperationVo().getOperationType();

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (ev.equals("stop_feeding") || ev.equals("auto_stop_feeding_completed")) {
                                    if (dialog != null && dialog.isShowing()) {
                                        dialog.dismiss();
                                    }

                                    final NormalDialog dialog = new NormalDialog(NewFeedingDetailActivity.this);
                                    dialog.content("投料单号：" + materialTankFeedingOrderCode + "，已完全停止，请确认！")//
                                            .btnNum(1)
                                            .btnText("确认")//
                                            .title("停止投料确认")
                                            //.showAnim(mBasIn)//
                                            //.dismissAnim(mBasOut)//
                                            .show();
                                    dialog.setCanceledOnTouchOutside(false);
                                    dialog.setOnBtnClickL(new OnBtnClickL() {
                                        @Override
                                        public void onBtnClick() {
                                            dialog.dismiss();
                                            userClickConfirm(orderId);
                                        }
                                    });

                                    isShowing = true;
                                } else if (ev.equals("start_feeding")) {
                                    if (!PermissionDaoImp.getInstance(NewFeedingDetailActivity.this).isHavePermission(ConstantPara.PDA_MATERIALTANKFEEDIINGORDER_COMPLETEFEEDING)
                                            && !PermissionDaoImp.getInstance(NewFeedingDetailActivity.this).isHavePermission(ConstantPara.PDA_MATERIALTANKFEEDIINGORDER_CONTINUEFEEDING)) {
                                        return;
                                    }

                                    if (!PermissionDaoImp.getInstance(NewFeedingDetailActivity.this).isHavePermission(ConstantPara.PDA_MATERIALTANKFEEDIINGORDER_CONTINUEFEEDING)) {
                                        final NormalDialog dialog = new NormalDialog(NewFeedingDetailActivity.this);
                                        dialog.content("投料单号：" + materialTankFeedingOrderCode + "，已完成投料，" +
                                                "请完成本次投料!")//
                                                .btnNum(1)
                                                .btnText("完成投料")//
                                                .title("完成投料")
                                                //.showAnim(mBasIn)//
                                                //.dismissAnim(mBasOut)//
                                                .show();
                                        dialog.setCanceledOnTouchOutside(false);

                                        dialog.setOnBtnClickL(
                                                new OnBtnClickL() {
                                                    @Override
                                                    public void onBtnClick() {
                                                        dialog.dismiss();
                                                        completeFeeding(orderId);
                                                    }
                                                });

                                        isShowing = true;
                                    } else if (!PermissionDaoImp.getInstance(NewFeedingDetailActivity.this).isHavePermission(ConstantPara.PDA_MATERIALTANKFEEDIINGORDER_COMPLETEFEEDING)) {
                                        final NormalDialog dialog = new NormalDialog(NewFeedingDetailActivity.this);
                                        dialog.content("投料单号：" + materialTankFeedingOrderCode + "，已完成投料，" +
                                                "请继续投料!")//
                                                .btnNum(1)
                                                .btnText("继续投料")//
                                                .title("继续投料")
                                                //.showAnim(mBasIn)//
                                                //.dismissAnim(mBasOut)//
                                                .show();
                                        dialog.setCanceledOnTouchOutside(false);

                                        dialog.setOnBtnClickL(
                                                new OnBtnClickL() {
                                                    @Override
                                                    public void onBtnClick() {
                                                        dialog.dismiss();
                                                        continueFeeding(orderId);

                                                        //继续投料重置isShowing
                                                        isShowing = false;
                                                    }
                                                });

                                        isShowing = true;
                                    } else {
                                        final NormalDialog dialog = new NormalDialog(NewFeedingDetailActivity.this);
                                        dialog.content("投料单号：" + materialTankFeedingOrderCode + "，已完成投料，" +
                                                "请选择继续投料，还是完成本次投料？")//
                                                .btnNum(2)
                                                .btnText("完成投料", "继续投料")//
                                                .title("完成投料")
                                                //.showAnim(mBasIn)//
                                                //.dismissAnim(mBasOut)//
                                                .show();
                                        dialog.setCanceledOnTouchOutside(false);

                                        dialog.setOnBtnClickL(
                                                new OnBtnClickL() {
                                                    @Override
                                                    public void onBtnClick() {
                                                        dialog.dismiss();
                                                        completeFeeding(orderId);
                                                    }
                                                },
                                                new OnBtnClickL() {
                                                    @Override
                                                    public void onBtnClick() {
                                                        dialog.dismiss();
                                                        continueFeeding(orderId);

                                                        //继续投料重置isShowing
                                                        isShowing = false;
                                                    }
                                                });

                                        isShowing = true;
                                    }
                                } else if (ev.equals("auto_stop_feeding")) {
                                    /*final NormalDialog dialog = new NormalDialog(NewFeedingDetailActivity.this);
                                    dialog.content("投料单号：" + materialTankFeedingOrderCode + "，投料已达到料罐投料上位已完全停止，请确认！")//
                                            .btnNum(1)
                                            .btnText("确认")//
                                            .title("停止投料确认")
                                            //.showAnim(mBasIn)//
                                            //.dismissAnim(mBasOut)//
                                            .show();
                                    dialog.setCanceledOnTouchOutside(false);
                                    dialog.setOnBtnClickL(new OnBtnClickL() {
                                        @Override
                                        public void onBtnClick() {
                                            dialog.dismiss();
                                            userClickConfirm(orderId);
                                        }
                                    });

                                    isShowing = true;*/

                                    if (isFullShowing) return;


                                    dialog = new ProgressDialog(NewFeedingDetailActivity.this);
                                    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                                    dialog.setCanceledOnTouchOutside(false);
                                    dialog.setCancelable(false);
                                    dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                                    dialog.setMessage("投料已达到料罐投料上位，本次投料正在停止，请等待…");
                                    dialog.show();

                                    //状态置为“停止中”
                                    order_status.setText("停止中");
                                    order_status.setTextColor(getResources().getColor(R.color.black));

                                    //遍历所有数据库操作记录，把不是“已完成”的状态都改为相应的即时状态，并刷新界面
                                    for (int i = 0; i < mList.size(); i++) {
                                        if (!mList.get(i).getMaterialTankFeedingRecordStatusDesc().contains("完成")) {
                                            mList.get(i).setMaterialTankFeedingRecordStatusDesc("停止中");
                                        }
                                    }
                                    mAdapter.notifyDataSetChanged();
                                    isFullShowing = true;

                                    //TODO：延迟10秒执行任务
                                    new Handler().postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            stopFeedCompletedRes();
                                        }
                                    }, 10000);
                                } /*else if (ev.equals("auto_stop_feeding_completed")) {
                                    if (dialog != null && dialog.isShowing()) {
                                        dialog.dismiss();
                                    }

                                    final NormalDialog dialog = new NormalDialog(NewFeedingDetailActivity.this);
                                    dialog.content("投料单号：" + materialTankFeedingOrderCode + "，已完全停止，请确认！")//
                                            .btnNum(1)
                                            .btnText("确认")//
                                            .title("停止投料确认")
                                            //.showAnim(mBasIn)//
                                            //.dismissAnim(mBasOut)//
                                            .show();
                                    dialog.setCanceledOnTouchOutside(false);
                                    dialog.setOnBtnClickL(new OnBtnClickL() {
                                        @Override
                                        public void onBtnClick() {
                                            dialog.dismiss();
                                            userClickConfirm(orderId);
                                        }
                                    });

                                    isShowing = true;
                                }*/
                            }
                        });

                    }
                }
            }

            @Override
            public void onFailure(@NotNull EventSource eventSource, @Nullable Throwable t, @Nullable okhttp3.Response response) {
                super.onFailure(eventSource, t, response);
            }

            @Override
            public void onOpen(@NotNull EventSource eventSource, @NotNull okhttp3.Response response) {
                super.onOpen(eventSource, response);
            }

        });

        eventSource.request();
    }

    private void getData(String orderId) {
        HttpHeaders headers = new HttpHeaders();
        headers.put("Authorization", PrefUtils.getString(this, "token", ""));
        OkGo.<LzyResponse<OrderDetailModel>>get(Urls.URL_GET_DETAIL + orderId)
                .tag(this)
                .headers(headers)
                .execute(new DialogCallback<LzyResponse<OrderDetailModel>>(this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<OrderDetailModel>> response) {
                        if (null != response.body().data) {
                            orderDetailModel = response.body().data;
                            materialTankFeedingOrderCode = orderDetailModel.getMaterialTankFeedingOrderCode();
                            order_id.setText(materialTankFeedingOrderCode);
                            materialTankNum = orderDetailModel.getMaterialTankNum();
                            tank_num.setText(materialTankNum);
                            bag_num.setText((int)orderDetailModel.getMaterialTankFeedingBagCount() + "");
                            need_origin.setText(orderDetailModel.getMaterialTankFeedingOrderSourceDesc());

                            start_feeding.setClickable(false);
                            start_feeding.setTextColor(getResources().getColor(R.color.colorWhite_lite));
                            start_feeding.setBackgroundResource(R.drawable.bg_feed_disable);
                            stop_feeding.setClickable(false);
                            stop_feeding.setTextColor(getResources().getColor(R.color.colorRed_lite));
                            stop_feeding.setBackgroundResource(R.drawable.bg_stop_disable);

                            String status = orderDetailModel.getMaterialTankFeedingOrderStatusDesc();
                            if (status.equals("待投料")) {
                                order_status.setTextColor(getResources().getColor(R.color.title_text_num));
                            } else if (status.contains("完成")) {
                                order_status.setTextColor(getResources().getColor(R.color.status_feeding_done));
                                ll_button.setVisibility(View.GONE);
                                ll_bag_num_obtain.setVisibility(View.GONE);
                                ll_three_obtain.setVisibility(View.GONE);
                                tv_back.setVisibility(View.VISIBLE);

                                deInitScanner();
                                deInitBarcodeManager();
                                if (emdkManager != null) {
                                    emdkManager.release();
                                    emdkManager = null;
                                    initFlag.set(false);
                                }
                            } else if (status.equals("投料中")) {
                                order_status.setTextColor(getResources().getColor(R.color.status_feeding));
                            } else {
                                order_status.setTextColor(getResources().getColor(R.color.title_text_quit));
                            }
                            order_status.setText(status);

                            if (!PermissionDaoImp.getInstance(NewFeedingDetailActivity.this).isHavePermission(ConstantPara.PDA_MATERIALTANKFEEDIINGRECORD_ADD)
                                    && !PermissionDaoImp.getInstance(NewFeedingDetailActivity.this).isHavePermission(ConstantPara.PDA_MATERIALTANKFEEDIINGORDER_STOPFEEDING)) {
                                ll_button.setVisibility(View.GONE);
                            } else if (!PermissionDaoImp.getInstance(NewFeedingDetailActivity.this).isHavePermission(ConstantPara.PDA_MATERIALTANKFEEDIINGORDER_STOPFEEDING)) {
                                stop_feeding.setVisibility(View.GONE);
                            } else if (!PermissionDaoImp.getInstance(NewFeedingDetailActivity.this).isHavePermission(ConstantPara.PDA_MATERIALTANKFEEDIINGRECORD_ADD)) {
                                start_feeding.setVisibility(View.GONE);
                            }

                            if (!PermissionDaoImp.getInstance(NewFeedingDetailActivity.this).isHavePermission(ConstantPara.PDA_MATERIALTANKFEEDIINGRECORD_LIST)) {
                                ll_record_list.setVisibility(View.GONE);
                                return;
                            }

                            //去查询数据库中是否有没有完成投料的记录
                            mList.clear();
                            if(status.equals("待投料") || status.equals("投料中")) {
                                ArrayList<DB_OperationRecord> db_operationRecords = OperationRecordDaoImp.getInstance(NewFeedingDetailActivity.this).getRecordsById(orderId);
                                if (db_operationRecords != null) {
                                    mList.addAll(db_operationRecords);
                                }
                            } else {
                                mList.addAll(response.body().data.getFeedRecords());
                            }

                            //如果有未开始的待投料单，则设置可以进行投料
                            if (status.equals("待投料")) {
                                if (OperationRecordDaoImp.getInstance(NewFeedingDetailActivity.this).isHaveNotStartedOrder(orderId)) {
                                    start_feeding.setClickable(true);
                                    start_feeding.setTextColor(getResources().getColor(R.color.colorWhite));
                                    start_feeding.setBackgroundResource(R.drawable.bg_feed_able);
                                }
                            }

                            //如果有进行中的待投料单，则设置可以停止投料
                            if (status.equals("投料中")) {
                                if (OperationRecordDaoImp.getInstance(NewFeedingDetailActivity.this).isHaveNotStartedOrder(orderId)) {
                                    start_feeding.setClickable(true);
                                    start_feeding.setTextColor(getResources().getColor(R.color.colorWhite));
                                    start_feeding.setBackgroundResource(R.drawable.bg_feed_able);
                                }

                                if (OperationRecordDaoImp.getInstance(NewFeedingDetailActivity.this).isHaveStartingOrder(orderId)) {
                                    stop_feeding.setClickable(true);
                                    stop_feeding.setTextColor(getResources().getColor(R.color.colorRed));
                                    stop_feeding.setBackgroundResource(R.drawable.bg_stop_able);
                                }
                            }

                            if (null == mList || mList.size() == 0) {
                                imgEmpty.setVisibility(View.VISIBLE);
                            } else {
                                imgEmpty.setVisibility(View.GONE);
                                mAdapter.notifyDataSetChanged();
                            }

                            mAdapter.setViewClickListener(new NewOrderDetailListAdapter.ViewClickListener() {
                                @Override
                                public void post_refresh() {
                                    if (null == mList || mList.size() == 0) {
                                        imgEmpty.setVisibility(View.VISIBLE);

                                        start_feeding.setClickable(false);
                                        start_feeding.setTextColor(getResources().getColor(R.color.colorWhite_lite));
                                        start_feeding.setBackgroundResource(R.drawable.bg_feed_disable);

                                    }
                                }
                            });
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<OrderDetailModel>> response) {
                        Toast.makeText(getApplicationContext(), response.getException().getMessage(),Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @Override
    public void onBackPressed() {
        //TODO：交付时改为不可以返回
        //super.onBackPressed();
    }

    public void initZebra(Context context) {
        boolean initResult = initFlag.compareAndSet(false, true);
        if (initResult) {
            XLog.i("ZEBRA初始化扫码设备");
            try {
                EMDKResults results = EMDKManager.getEMDKManager(getApplicationContext(), this);
                XLog.i("ZEBRA初始化结果" + results.statusCode);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            XLog.i("ZEBRA已经初始化");
        }

    }

    @Override
    public void onOpened(EMDKManager emdkManager) {
        this.emdkManager = emdkManager;
        // Acquire the barcode manager resources
        initBarcodeManager();
        // Enumerate scanner devices
        enumerateScannerDevices();
    }

    @Override
    public void onClosed() {
        if (emdkManager != null) {
            emdkManager.release();
            emdkManager = null;
        }
    }

    private void initScanner() {
        if (scanner == null) {
            if (barcodeManager != null) {
                scanner = barcodeManager.getDevice(readScannerInfo);
                setDecoders();
            }
            if (scanner != null) {
                scanner.addDataListener(this);
                scanner.addStatusListener(this);
                try {
                    scanner.enable();
                } catch (ScannerException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void initBarcodeManager() {
        barcodeManager = (BarcodeManager) emdkManager.getInstance(EMDKManager.FEATURE_TYPE.BARCODE);
        // Add connection listener
        if (barcodeManager != null) {
            barcodeManager.addConnectionListener(this);
        }
    }

    private void deInitBarcodeManager() {
        if (emdkManager != null) {
            emdkManager.release(EMDKManager.FEATURE_TYPE.BARCODE);
        }
    }

    private void deInitScanner() {
        if (scanner != null) {
            try {
                scanner.disable();
                scanner.removeDataListener(this);
                scanner.removeStatusListener(this);
                scanner.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
            scanner = null;
        }
    }

    private void setDecoders() {
        if (scanner != null) {
            try {
                ScannerConfig config = scanner.getConfig();
                // Set EAN8
                config.decoderParams.ean8.enabled = true;
                // Set EAN13
                config.decoderParams.ean13.enabled = true;
                // Set Code39
                config.decoderParams.code39.enabled = true;
                //Set Code128
                config.decoderParams.code128.enabled = true;
                scanner.setConfig(config);
            } catch (ScannerException e) {
                e.printStackTrace();
            }
        }
    }

    private void enumerateScannerDevices() {
        if (barcodeManager != null) {
            List<ScannerInfo> deviceList = barcodeManager.getSupportedDevicesInfo();
            XLog.i("enumerateScannerDevices size = " + deviceList.size());
            if ((deviceList != null) && (deviceList.size() != 0)) {
                Iterator<ScannerInfo> it = deviceList.iterator();
                while (it.hasNext()) {
                    ScannerInfo scnInfo = it.next();
                    XLog.i("scnInfo friendlyName=%s,isDefaultScanner=%s", scnInfo.getFriendlyName(), scnInfo.isDefaultScanner());
                    if (scnInfo.isDefaultScanner()) {
                        readScannerInfo = scnInfo;
                        deInitScanner();
                        initScanner();
                        break;
                    }
                }
            }
        }
    }

    @Override
    public void onConnectionChange(ScannerInfo scannerInfo, BarcodeManager.ConnectionState connectionState) {
        String scannerName = "";
        String scannerNameExtScanner = scannerInfo.getFriendlyName();
        scannerName = scannerInfo.getFriendlyName();
        if (scannerName.equalsIgnoreCase(scannerNameExtScanner)) {
            switch (connectionState) {
                case CONNECTED:
                    bSoftTriggerSelected = false;
                    synchronized (lock) {
                        initScanner();
                        bExtScannerDisconnected = false;
                    }
                    break;
                case DISCONNECTED:
                    bExtScannerDisconnected = true;
                    synchronized (lock) {
                        deInitScanner();
                    }
                    break;
            }
        } else {
            bExtScannerDisconnected = false;
        }
    }

    @Override
    public void onData(ScanDataCollection scanDataCollection) {
        if ((scanDataCollection != null) && (scanDataCollection.getResult() == ScannerResults.SUCCESS)) {
            ArrayList<ScanDataCollection.ScanData> scanData = scanDataCollection.getScanData();
            for (ScanDataCollection.ScanData data : scanData) {
                XLog.i("扫码结果data = %s,type=%s", data.getData(), data.getLabelType());
                //activity.handleQrCode(data.getData());

                //判断当前是否有进行中的记录，有的话不进行操作
                if (OperationRecordDaoImp.getInstance(this).isHaveStartingOrder(orderId)) return;

                //判断当前是否是扫的物料码，如果是去进行合法性校验，再进行数据库表插入或者更新
                if (OperationRecordDaoImp.getInstance(this).isMaterialCode(orderId, data.getData())) {
                    Log.i("扫码结果data = %s,type=%s", "是物料码");

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            checkMaterialCode(orderId, data.getData());
                        }
                    });

                } else {
                    Log.i("扫码结果data = %s,type=%s", "是缓存位码");

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            checkStockLocationCode(data.getData());
                        }
                    });
                }
            }
        }
    }

    @Override
    public void onStatus(StatusData statusData) {
        StatusData.ScannerStates state = statusData.getState();
        switch (state) {
            case IDLE:
                // set trigger type
                if (bSoftTriggerSelected) {
                    scanner.triggerType = Scanner.TriggerType.SOFT_ONCE;
                    bSoftTriggerSelected = false;
                } else {
                    scanner.triggerType = Scanner.TriggerType.HARD;
                }
                // submit read
                if (!scanner.isReadPending() && !bExtScannerDisconnected) {
                    try {
                        scanner.read();
                    } catch (ScannerException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case WAITING:
                break;
            case SCANNING:
                break;
            case DISABLED:
                break;
            case ERROR:
                break;
            default:
                break;
        }
    }

    @OnClick({R.id.ll_bag_num_obtain, R.id.ll_three_obtain, R.id.start_feeding, R.id.stop_feeding, R.id.tv_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_three_obtain:
                getThreeWayStatus();
                break;
            case R.id.ll_bag_num_obtain:
                //TODO:临时用这里模拟上料位触发
                setAutoStopFeed();
                //getBagCount();
                break;
            case R.id.start_feeding:
                if (three_status.getText().equals("未开启")) {
                    final NormalDialog dialog = new NormalDialog(NewFeedingDetailActivity.this);
                    dialog.content("三通阀未开启！")//
                            .btnNum(1)
                            .btnText("知道了")//
                            .title("投料失败")
                            //.showAnim(mBasIn)//
                            //.dismissAnim(mBasOut)//
                            .show();
                    dialog.setCanceledOnTouchOutside(false);
                    dialog.setOnBtnClickL(new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            dialog.dismiss();
                        }
                    });
                    return;
                }

                //检查物料和缓存为码是否齐备
                if(!OperationRecordDaoImp.getInstance(NewFeedingDetailActivity.this).isCodeCompleted(orderId)) {
                    final NormalDialog dialog = new NormalDialog(NewFeedingDetailActivity.this);
                    dialog.content("物料码对应的缓存位码缺失！")//
                            .btnNum(1)
                            .btnText("知道了")//
                            .title("投料失败")
                            //.showAnim(mBasIn)//
                            //.dismissAnim(mBasOut)//
                            .show();
                    dialog.setCanceledOnTouchOutside(false);
                    dialog.setOnBtnClickL(new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            dialog.dismiss();
                        }
                    });
                    return;
                }

                startFeeding();
                break;
            case R.id.stop_feeding:
                final NormalDialog dialog = new NormalDialog(NewFeedingDetailActivity.this);
                dialog.content("是否确定停止投料？")
                        .btnNum(2)
                        .btnText("取消", "确认")
                        .title("停止投料确认")
                        //.showAnim(mBasIn)//
                        //.dismissAnim(mBasOut)//
                        .show();
                dialog.setCanceledOnTouchOutside(false);

                dialog.setOnBtnClickL(
                        new OnBtnClickL() {
                            @Override
                            public void onBtnClick() {
                                dialog.dismiss();
                            }
                        },
                        new OnBtnClickL() {
                            @Override
                            public void onBtnClick() {
                                dialog.dismiss();
                                stopFeeding();
                            }
                        });
                break;
            case R.id.tv_back:
                OperationRecordDaoImp.getInstance(NewFeedingDetailActivity.this).deleteRecordById(orderId);
                finish();
                break;
        }
    }

    private void setAutoStopFeed() {
        HttpHeaders headers = new HttpHeaders();
        headers.put("Authorization", PrefUtils.getString(this, "token", ""));
        OkGo.<LzyResponse<String>>get(Urls.URL_TEMP_AUTO_STOP + orderId)
                .tag(this)
                .headers(headers)
                //.upRequestBody(body)
                .execute(new DialogCallback<LzyResponse<String>>(this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<String>> response) {
                        if (null != response.body().msg && response.body().msg.contains("成功")) {

                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<String>> response) {
                        Toast.makeText(getApplicationContext(), response.getException().getMessage(),Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void startFeeding() {
        tmpShutdown();

        Map<String ,Object> map=new HashMap<>();
        map.put("materialTankFeedingOrderId", orderId);
        ArrayList<FeedRecord> feedRecords = new ArrayList<>();
        for (DB_OperationRecord db_operationRecord: mList){
            if (db_operationRecord.getMaterialTankFeedingRecordStatusDesc().equals("未开始")) {
                FeedRecord feedRecord = new FeedRecord();
                feedRecord.setMaterialCode(db_operationRecord.getMaterialCode());
                feedRecord.setStockLocationCode(db_operationRecord.getStockLocationCode());
                feedRecord.setScanPalletCodeTime(db_operationRecord.getScanPalletCodeTime());
                feedRecord.setScanLocationCodeTime(db_operationRecord.getScanLocationCodeTime());
                feedRecords.add(feedRecord);
            }
        }
        map.put("recordList", feedRecords);
        Gson gg=new Gson();
        String json =gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        HttpHeaders headers = new HttpHeaders();
        headers.put("Authorization", PrefUtils.getString(this, "token", ""));
        OkGo.<LzyResponse<String>>post(Urls.URL_START_FEEDING)
                .tag(this)
                .upRequestBody(body)
                .isMultipart(false)
                .headers(headers)
                .execute(new DialogCallback<LzyResponse<String>>(this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<String>> response) {
                        if (null != response.body().msg) {
                            if (response.body().msg.contains("成功")) {
                                //OperationRecordDaoImp.getInstance(NewFeedingDetailActivity.this).deleteAll();
                                //getData(orderId);

                                //状态置为“投料中”
                                order_status.setText("投料中");
                                order_status.setTextColor(getResources().getColor(R.color.status_feeding));

                                //遍历所有数据库操作记录，把不是“已完成”的状态都改为相应的即时状态，并刷新界面
                                OperationRecordDaoImp.getInstance(NewFeedingDetailActivity.this).upDateStatus(NewFeedingDetailActivity.this, orderId, "进行中");
                                for (int i = 0; i < mList.size(); i++) {
                                    if (!mList.get(i).getMaterialTankFeedingRecordStatusDesc().contains("完成")) {
                                        mList.get(i).setMaterialTankFeedingRecordStatusDesc("进行中");
                                    }
                                }
                                mAdapter.notifyDataSetChanged();

                                start_feeding.setClickable(false);
                                start_feeding.setTextColor(getResources().getColor(R.color.colorWhite_lite));
                                start_feeding.setBackgroundResource(R.drawable.bg_feed_disable);
                                stop_feeding.setClickable(true);
                                stop_feeding.setTextColor(getResources().getColor(R.color.colorRed));
                                stop_feeding.setBackgroundResource(R.drawable.bg_stop_able);
                            }
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<String>> response) {
                        Toast.makeText(getApplicationContext(), response.getException().getMessage(),Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void stopFeeding() {
        HttpHeaders headers = new HttpHeaders();
        headers.put("Authorization", PrefUtils.getString(this, "token", ""));
        OkGo.<LzyResponse<String>>post(Urls.URL_STOP_FEEDING + orderId)
                .tag(this)
                .headers(headers)
                .execute(new DialogCallback<LzyResponse<String>>(this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<String>> response) {
                        if (null != response.body().msg && response.body().msg.contains("成功")) {
                            //维持一个正在停止的加载框
                            dialog = new ProgressDialog(NewFeedingDetailActivity.this);
                            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                            dialog.setCanceledOnTouchOutside(false);
                            dialog.setCancelable(false);
                            dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                            dialog.setMessage("本次投料正在停止，请等待…");
                            dialog.show();


                            //状态置为“停止中”
                            order_status.setText("停止中");
                            order_status.setTextColor(getResources().getColor(R.color.black));

                            //遍历所有数据库操作记录，把不是“已完成”的状态都改为相应的即时状态，并刷新界面
                            for (int i = 0; i < mList.size(); i++) {
                                if (!mList.get(i).getMaterialTankFeedingRecordStatusDesc().contains("完成")) {
                                    mList.get(i).setMaterialTankFeedingRecordStatusDesc("停止中");
                                }
                            }
                            mAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<String>> response) {
                        Toast.makeText(getApplicationContext(), response.getException().getMessage(),Toast.LENGTH_SHORT).show();
                    }
                });

        tmpShutdown();

    }

    private void stopFeedCompletedRes() {
        HttpHeaders headers = new HttpHeaders();
        headers.put("Authorization", PrefUtils.getString(this, "token", ""));
        OkGo.<LzyResponse<String>>post(Urls.URL_STOP_FEED_COMPLETED + orderId)
                .tag(this)
                .headers(headers)
                .execute(new JsonCallback<LzyResponse<String>>() {
                    @Override
                    public void onSuccess(Response<LzyResponse<String>> response) {
                        if (null != response.body().msg) {
                            if (response.body().msg.contains("成功")) {

                            }
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<String>> response) {
                        Toast.makeText(getApplicationContext(), "非法投料缓存位码，请重新扫描！", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void tmpShutdown() {
        //TODO：临时模拟
        HttpHeaders headers = new HttpHeaders();
        headers.put("Authorization", PrefUtils.getString(this, "token", ""));
        //模拟设置两个机械臂都停止
        Map<String ,Object> map=new HashMap<>();
        map.put("address", "VW224");
        map.put("value", "0");

        Gson gg=new Gson();
        String json =gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<LzyResponse<String>>get(Urls.URL_TEMP + "?address=" + "VW224" + "&value=" + 0)
                .tag(this)
                .headers(headers)
                //.upRequestBody(body)
                .execute(new DialogCallback<LzyResponse<String>>(this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<String>> response) {
                        if (null != response.body().msg && response.body().msg.contains("成功")) {

                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<String>> response) {
                        Toast.makeText(getApplicationContext(), response.getException().getMessage(),Toast.LENGTH_SHORT).show();
                    }
                });

        Map<String ,Object> map2=new HashMap<>();
        map2.put("address", "VW226");
        map2.put("value", "0");

        Gson gg2=new Gson();
        String json2 =gg2.toJson(map2);

        RequestBody body2 = RequestBody.create(JSON, json2);
        OkGo.<LzyResponse<String>>get(Urls.URL_TEMP + "?address=" + "VW226" + "&value=" + 0)
                .tag(this)
                .headers(headers)
                //.upRequestBody(body2)
                .execute(new DialogCallback<LzyResponse<String>>(this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<String>> response) {
                        if (null != response.body().msg && response.body().msg.contains("成功")) {

                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<String>> response) {
                        Toast.makeText(getApplicationContext(), response.getException().getMessage(),Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void tmpStartUp() {
        //TODO：临时模拟
        HttpHeaders headers = new HttpHeaders();
        headers.put("Authorization", PrefUtils.getString(this, "token", ""));
        //模拟设置两个机械臂都停止
        Map<String ,Object> map=new HashMap<>();
        map.put("address", "VW224");
        map.put("value", "1");

        Gson gg=new Gson();
        String json =gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<LzyResponse<String>>get(Urls.URL_TEMP + "?address=" + "VW224" + "&value=" + 1)
                .tag(this)
                .headers(headers)
                //.upRequestBody(body)
                .execute(new DialogCallback<LzyResponse<String>>(this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<String>> response) {
                        if (null != response.body().msg && response.body().msg.contains("成功")) {

                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<String>> response) {
                        Toast.makeText(getApplicationContext(), response.getException().getMessage(),Toast.LENGTH_SHORT).show();
                    }
                });

        Map<String ,Object> map2=new HashMap<>();
        map2.put("address", "VW226");
        map2.put("value", "1");

        Gson gg2=new Gson();
        String json2 =gg2.toJson(map2);

        RequestBody body2 = RequestBody.create(JSON, json2);
        OkGo.<LzyResponse<String>>get(Urls.URL_TEMP + "?address=" + "VW226" + "&value=" + 1)
                .tag(this)
                .headers(headers)
                //.upRequestBody(body2)
                .execute(new DialogCallback<LzyResponse<String>>(this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<String>> response) {
                        if (null != response.body().msg && response.body().msg.contains("成功")) {

                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<String>> response) {
                        Toast.makeText(getApplicationContext(), response.getException().getMessage(),Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void getBagCount() {
        HttpHeaders headers = new HttpHeaders();
        headers.put("Authorization", PrefUtils.getString(this, "token", ""));
        OkGo.<LzyResponse<String>>get(Urls.URL_GET_BAGCOUNT + orderId)
                .tag(this)
                .headers(headers)
                .execute(new JsonCallback<LzyResponse<String>>() {
                    @Override
                    public void onSuccess(Response<LzyResponse<String>> response) {
                        if (null != response.body().data) {
                            bag_num.setText(response.body().data);
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<String>> response) {
                        Toast.makeText(getApplicationContext(), response.getException().getMessage(),Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void getThreeWayStatus() {
        HttpHeaders headers = new HttpHeaders();
        headers.put("Authorization", PrefUtils.getString(this, "token", ""));
        OkGo.<LzyResponse<String>>get(Urls.URL_GET_THREE + "?materialTankNum=" + materialTankNum)
                .tag(this)
                .headers(headers)
                .execute(new DialogCallback<LzyResponse<String>>(this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<String>> response) {
                        if (null != response.body().msg) {
                            if (response.body().msg.equals("Y")) {
                                three_status.setText("已开启");
                                three_status.setTextColor(getResources().getColor(R.color.white));
                                three_status.setBackgroundResource(R.drawable.bg_item_three_open);
                            } else {
                                three_status.setText("未开启");
                                three_status.setTextColor(getResources().getColor(R.color.title_text_num));
                                three_status.setBackgroundResource(R.drawable.bg_item_three_close);
                            }
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<String>> response) {
                        Toast.makeText(getApplicationContext(), response.getException().getMessage(),Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void checkMaterialCode(String materialTankFeedingOrderId, String materialCode) {
        Map<String ,Object> map=new HashMap<>();
        map.put("materialTankFeedingOrderId", materialTankFeedingOrderId);
        map.put("materialCode", materialCode);

        Gson gg=new Gson();
        String json =gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);

        HttpHeaders headers = new HttpHeaders();
        headers.put("Authorization", PrefUtils.getString(this, "token", ""));
        OkGo.<LzyResponse<String>>post(Urls.URL_CHECK_MATERIALCODE)
                .tag(this)
                .headers(headers)
                .upRequestBody(body)
                .isMultipart(false)
                .execute(new DialogCallback<LzyResponse<String>>(this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<String>> response) {
                        if (null != response.body().msg) {
                            if (response.body().msg.contains("成功")) {
                                OperationRecordDaoImp.getInstance(NewFeedingDetailActivity.this).AddCodeAndTime(orderId, materialCode);

                /*DB_OperationRecord db_operationRecord = OperationRecordDaoImp.getInstance(this).getRecordById(orderId);
                if (db_operationRecord != null) {
                    mList.add(0, db_operationRecord);
                }*/
                                mList.clear();
                                mList.addAll(OperationRecordDaoImp.getInstance(NewFeedingDetailActivity.this).getRecordsById(orderId));

                                if (null == mList || mList.size() == 0) {
                                    imgEmpty.setVisibility(View.VISIBLE);
                                } else {
                                    imgEmpty.setVisibility(View.GONE);
                                    mAdapter.notifyDataSetChanged();
                                }

                                start_feeding.setClickable(true);
                                start_feeding.setTextColor(getResources().getColor(R.color.colorWhite));
                                start_feeding.setBackgroundResource(R.drawable.bg_feed_able);
                            }
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<String>> response) {
                        final NormalDialog dialog = new NormalDialog(NewFeedingDetailActivity.this);
                        dialog.content("扫描的物料编码不存在当前投料罐中的投料单物料中！")//
                                .btnNum(1)
                                .btnText("知道了")//
                                .title("扫描失败")
                                //.showAnim(mBasIn)//
                                //.dismissAnim(mBasOut)//
                                .show();
                        dialog.setCanceledOnTouchOutside(false);
                        dialog.setOnBtnClickL(new OnBtnClickL() {
                            @Override
                            public void onBtnClick() {
                                dialog.dismiss();
                            }
                        });
                    }
                });
    }

    private void checkStockLocationCode(String checkStockLocationCode) {
        HttpHeaders headers = new HttpHeaders();
        headers.put("Authorization", PrefUtils.getString(this, "token", ""));
        OkGo.<LzyResponse<String>>post(Urls.URL_CHECK_STOCKLOCATIONCODE + checkStockLocationCode)
                .tag(this)
                .headers(headers)
                .execute(new DialogCallback<LzyResponse<String>>(this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<String>> response) {
                        if (null != response.body().msg) {
                            if (response.body().msg.contains("成功")) {
                                OperationRecordDaoImp.getInstance(NewFeedingDetailActivity.this).AddCodeAndTime(orderId, checkStockLocationCode);

                /*DB_OperationRecord db_operationRecord = OperationRecordDaoImp.getInstance(this).getRecordById(orderId);
                if (db_operationRecord != null) {
                    mList.add(0, db_operationRecord);
                }*/
                                mList.clear();
                                mList.addAll(OperationRecordDaoImp.getInstance(NewFeedingDetailActivity.this).getRecordsById(orderId));

                                if (null == mList || mList.size() == 0) {
                                    imgEmpty.setVisibility(View.VISIBLE);
                                } else {
                                    imgEmpty.setVisibility(View.GONE);
                                    mAdapter.notifyDataSetChanged();

                                    start_feeding.setClickable(true);
                                    start_feeding.setTextColor(getResources().getColor(R.color.colorWhite));
                                    start_feeding.setBackgroundResource(R.drawable.bg_feed_able);
                                }
                                /*runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (null == mList || mList.size() == 0) {
                                            imgEmpty.setVisibility(View.VISIBLE);
                                        } else {
                                            imgEmpty.setVisibility(View.GONE);
                                            mAdapter.notifyDataSetChanged();
                                        }
                                    }
                                });*/
                            }
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<String>> response) {
                        final NormalDialog dialog = new NormalDialog(NewFeedingDetailActivity.this);
                        dialog.content("非法投料缓存位码，请重新扫描！")//
                                .btnNum(1)
                                .btnText("知道了")//
                                .title("扫描失败")
                                //.showAnim(mBasIn)//
                                //.dismissAnim(mBasOut)//
                                .show();
                        dialog.setCanceledOnTouchOutside(false);
                        dialog.setOnBtnClickL(new OnBtnClickL() {
                            @Override
                            public void onBtnClick() {
                                dialog.dismiss();
                            }
                        });
                    }
                });
    }

    private void userClickConfirm(String orderId) {
        HttpHeaders headers = new HttpHeaders();
        headers.put("Authorization", PrefUtils.getString(this, "token", ""));
        OkGo.<LzyResponse<String>>post(Urls.URL_USER_CONFIRM + orderId)
                .tag(this)
                .headers(headers)
                .execute(new DialogCallback<LzyResponse<String>>(this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<String>> response) {
                        if (null != response.body().msg) {
                            if (response.body().msg.contains("成功")) {
                                order_status.setText("投料完成");
                                order_status.setTextColor(getResources().getColor(R.color.status_feeding_done));
                                ll_button.setVisibility(View.GONE);
                                ll_bag_num_obtain.setVisibility(View.GONE);
                                ll_three_obtain.setVisibility(View.GONE);

                                EventBus.getDefault().post(new MessageEvent(ORDERID, orderId));

                                //遍历所有数据库操作记录，把不是“已完成”的状态都改为相应的即时状态，并刷新界面
                                OperationRecordDaoImp.getInstance(NewFeedingDetailActivity.this).upDateStatus(NewFeedingDetailActivity.this, orderId, "投料完成");
                                for (int i = 0; i < mList.size(); i++) {
                                    if (!mList.get(i).getMaterialTankFeedingRecordStatusDesc().contains("完成")) {
                                        mList.get(i).setMaterialTankFeedingRecordStatusDesc("投料完成");
                                    }
                                }
                                mAdapter.notifyDataSetChanged();

                                tv_back.setVisibility(View.VISIBLE);

                                tmpStartUp();
                            }
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<String>> response) {
                        Toast.makeText(getApplicationContext(), response.getException().getMessage(),Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void continueFeeding(String orderId) {
        HttpHeaders headers = new HttpHeaders();
        headers.put("Authorization", PrefUtils.getString(this, "token", ""));
        OkGo.<LzyResponse<String>>post(Urls.URL_CONTINUE_FEEDING + orderId)
                .tag(this)
                .headers(headers)
                .execute(new DialogCallback<LzyResponse<String>>(this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<String>> response) {
                        if (null != response.body().msg) {
                            if (response.body().msg.contains("成功")) {
                                //遍历所有数据库操作记录，把不是“已完成”的状态都改为相应的即时状态，要放在mAdapter.notifyDataSetChanged()之前操作
                                OperationRecordDaoImp.getInstance(NewFeedingDetailActivity.this).upDateStatus(NewFeedingDetailActivity.this, orderId, "投料完成");

                                for (int i = 0; i < mList.size(); i++) {
                                    if (!mList.get(i).getMaterialTankFeedingRecordStatusDesc().contains("完成")) {
                                        mList.get(i).setMaterialTankFeedingRecordStatusDesc("投料完成");
                                    }
                                }
                                mAdapter.notifyDataSetChanged();


                                start_feeding.setClickable(false);
                                start_feeding.setTextColor(getResources().getColor(R.color.colorWhite_lite));
                                start_feeding.setBackgroundResource(R.drawable.bg_feed_disable);
                                stop_feeding.setClickable(false);
                                stop_feeding.setTextColor(getResources().getColor(R.color.colorRed_lite));
                                stop_feeding.setBackgroundResource(R.drawable.bg_stop_disable);

                            }
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<String>> response) {
                        Toast.makeText(getApplicationContext(), response.getException().getMessage(),Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void completeFeeding(String orderId) {
        HttpHeaders headers = new HttpHeaders();
        headers.put("Authorization", PrefUtils.getString(this, "token", ""));
        OkGo.<LzyResponse<String>>post(Urls.URL_COMPLETE_FEEDING + orderId)
                .tag(this)
                .headers(headers)
                .execute(new DialogCallback<LzyResponse<String>>(this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<String>> response) {
                        if (null != response.body().msg) {
                            if (response.body().msg.contains("成功")) {
                                final NormalDialog dialog = new NormalDialog(NewFeedingDetailActivity.this);
                                dialog.content("投料单号：" + materialTankFeedingOrderCode + "，已完全停止，请确认！")//
                                        .btnNum(1)
                                        .btnText("确认")//
                                        .title("停止投料确认")
                                        //.showAnim(mBasIn)//
                                        //.dismissAnim(mBasOut)//
                                        .show();
                                dialog.setCanceledOnTouchOutside(false);
                                dialog.setOnBtnClickL(new OnBtnClickL() {
                                    @Override
                                    public void onBtnClick() {
                                        dialog.dismiss();
                                        userClickConfirm(orderId);
                                    }
                                });
                            }
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<String>> response) {
                        Toast.makeText(getApplicationContext(), response.getException().getMessage(),Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        eventSource.cancel();
        deInitScanner();
        deInitBarcodeManager();
        if (emdkManager != null) {
            emdkManager.release();
            emdkManager = null;
            initFlag.set(false);
        }
        if (timer != null) {
            timer = null;
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onShutDown(MessageEvent eventMsg) {
        String msg = eventMsg.getMessage();
        if (eventMsg.getType() == 8) {
            // activity关闭，从栈中移除
            //appManager.finishActivity(this);
            if (NewFeedingDetailActivity.this.getWindow().getDecorView().getVisibility() == View.VISIBLE) {
                Toast.makeText(this, "登录已过期", Toast.LENGTH_SHORT).show();
                Log.i("登录过期走到这里=========", "NewFeedingDetailActivity");
                Intent intent = new Intent(NewFeedingDetailActivity.this, LoginActivity.class);
                intent.putExtra("isUpdate", true);
                startActivity(intent);
            }
        }
    }
}
